package com.chinda.modules.job.utils;


import cn.hutool.core.util.StrUtil;
import com.chinda.common.constants.CommonConstant;
import com.chinda.common.enums.TaskStatusEnum;
import com.chinda.common.utils.SpringContextUtils;
import com.chinda.modules.job.entity.ScheduleJobEntity;
import com.chinda.modules.job.entity.ScheduleJobLogEntity;
import com.chinda.modules.job.service.ScheduleJobLogService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.lang.reflect.Method;


/**
 * 定时任务
 *
 *
 * @author chinda
 * @date 2021-07-09 19:09:10
 */
@Slf4j
public class ScheduleJob extends QuartzJobBean {


    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {


		String name = context.getMergedJobDataMap()
				.get(CommonConstant.JOB_PARAM_KEY).getClass().getClassLoader().getClass().getName();
		String name1 = ScheduleJobEntity.class.getClassLoader().getClass().getName();
		log.info("job classloader {}, origin classloader {}", name, name1);

		ScheduleJobEntity scheduleJob = (ScheduleJobEntity) context.getMergedJobDataMap()
        		.get(CommonConstant.JOB_PARAM_KEY);

        
        // 获取spring bean
        ScheduleJobLogService scheduleJobLogService = (ScheduleJobLogService) SpringContextUtils.getBean("scheduleJobLogService");
        
        // 数据库保存执行记录
        ScheduleJobLogEntity jobLog = new ScheduleJobLogEntity();
        jobLog.setJobId(scheduleJob.getJobId());
        jobLog.setBeanName(scheduleJob.getBeanName());
        jobLog.setParams(scheduleJob.getParams());
        
        // 任务开始时间
        long startTime = System.currentTimeMillis();
        
        try {
            // 执行任务
        	log.info("任务准备执行，任务ID：" + scheduleJob.getJobId());

			Object target = SpringContextUtils.getBean(scheduleJob.getBeanName());
			Method method = target.getClass().getDeclaredMethod("run", String.class);
			method.invoke(target, scheduleJob.getParams());
			
			// 任务执行总时长
			long times = System.currentTimeMillis() - startTime;
			jobLog.setTimes((int)times);
			// 任务状态    0：成功    1：失败
			jobLog.setStatus(TaskStatusEnum.SUCCESS);
			
			log.info("任务执行完毕，任务ID：" + scheduleJob.getJobId() + "  总共耗时：" + times + "毫秒");
		} catch (Exception e) {
			log.error("任务执行失败，任务ID：" + scheduleJob.getJobId(), e);
			
			//任务执行总时长
			long times = System.currentTimeMillis() - startTime;
			jobLog.setTimes((int)times);
			
			// 任务状态    0：成功    1：失败
			jobLog.setStatus(TaskStatusEnum.FAILURE);
			jobLog.setError(StrUtil.sub(e.toString(), 0, 2000));
		}finally {
			scheduleJobLogService.save(jobLog);
		}
    }
}
